var page = 1;

$(document).ready(function() {
	displayFaculty();
	displayProject();
	var currentUrl = window.location.href;
	if(currentUrl.indexOf('#') != -1){
		page = currentUrl.slice(currentUrl.indexOf('#') + 1);
	}
	getFaculty(page);
	getCountFaculty();
});

$(window).bind('hashchange', function() {
	location.reload();
});

function getFaculty(page){
	
	var params = {
		action: 'getByLimit',
		fromFaculty: LIMIT_FACULTY * (parseInt(page) - 1),
		toFaculty: LIMIT_FACULTY
	};
	sendRequest(URL_FACULTY, 'GET', params, function(res){
		var data = JSON.parse(res);
		$('#facultyLargeList').html('');
		for(var index in data){
			$('#facultyLargeList').append(drawLargeFaculty(data[index]));
		}
	}, function(err){
	});
}

function drawLargeFaculty(faculty){
	var href = FACULTY_DETAIL+'#'+faculty.Id;
	var tempReturn = drawDiv('col-md-6 col-lg-6 col-xs-12 col-sm-6 form-group');
	var facultyImage = drawDiv('col-md-8 col-lg-8 col-sm-8 col-xs-6');
	facultyImage.append(drawA('', href, '').append(drawImage(faculty.Image)));
	var facultyInfo = drawDiv('col-md-8 col-lg-8 col-sm-8 col-xs-6');
	facultyInfo.append(drawP(TEXT_MUTED, '').append(drawA('', href, '').append(drawLabel('',faculty.Name))));
	facultyInfo.append(drawP(TEXT_MUTED, '').append(drawLabel('',faculty.Diploma)));
	facultyInfo.append(drawP(TEXT_MUTED, 'Bộ môn: ' + faculty.Department));
	tempReturn.append(drawDiv('panel panel-default').append(drawDiv('panel-body').append(drawDiv('row').append(facultyImage).append(facultyInfo))));
	return tempReturn;
}

function getCountFaculty(){
	var params = {
		action: 'getCountRow'
	};
	sendRequest(URL_FACULTY, 'GET', params, function(res){
		var data = JSON.parse(res);
		var countPage = Math.round(data.countRow / LIMIT_FACULTY);
		if(data.countRow % LIMIT_FACULTY > 0 && data.countRow % LIMIT_FACULTY < LIMIT_FACULTY/2){
			countPage++;
		}
		$('#pageList').html('');
		if(currentPage > countPage){
			currentPage = countPage;
		}
		if(currentPage > 5){
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, 1)));
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage - 1)));
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage)));
			if(currentPage + 1 < countPage){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage + 1)));
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, countPage)));
			} else if(currentPage + 1 == countPage){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, countPage)));
			}
		} else {
			for(var index = 1; index <= countPage; index++){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, index)));
			}
		}
	}, function(err){
	});
}